<template>
  <c-back-wrap :loading="loading" go-page="经销商合作终止管理" :before-call-back="$goBackCall" :current-page="isEdit?'编辑':'新增'">
    <c-title title="经销商-客户基本信息">
      <CustomerBaseInfo
        ref="customerBaseInfo"
        v-model="customerFormData"
        :before-params="paramsJson=>{
          paramsJson.filtersRaw.push({id:'oneCategoryCode',property:'oneCategoryCode',value:'Z230',operator:'<>'})
          $codeOrName(paramsJson.filtersRaw, 'code', 'name')
          if(!paramsJson.paramsRaw){
            paramsJson.paramsRaw = {}
          }
          paramsJson.paramsRaw.changeType = 'I'
          return paramsJson
        }"
        :detail="detail"
        :disabled="isEdit"
        show-column="cityLevelName cooperateStart"
        :start-observe="startObserve"
        @change="handleCustomerChange"
      />
    </c-title>
    <c-title title="经销商-合作终止信息">
      <QupFormContainer :column="3">
        <el-form ref="endForm" :model="cooperationEndDTO" :rules="formRules" label-width="160px">
          <el-form-item key="reason" prop="reason" label="合作终止原因" :span="24">
            <el-input v-model="cooperationEndDTO.reason" type="textarea" show-word-limit maxlength="1024" :autosize="{minRows: 2}" placeholder="合作终止原因" />
          </el-form-item>
          <el-form-item key="type" prop="type" label="合作终止类型" :span="24">
            <CDictRadio v-model="cooperationEndDTO.type" dict-type-code="CTM_COOPERATE_END_TYPE" @change="handleTypeChange" />
          </el-form-item>
          <el-form-item v-if="isHandover" key="isTransferSales" prop="isTransferSales" label="是否转让销量">
            <c-dict-select v-model="cooperationEndDTO.isTransferSales" dict-type-code="BOOLEANS" placeholder="是否转让销量" clearable />
          </el-form-item>
          <el-form-item key="distributionType" prop="distributionType" label="未完成配送订单处理方式">
            <c-dict-select v-model="cooperationEndDTO.distributionType" :exclude="!isHandover?['B']:[]" dict-type-code="CTM_TOBE_DISTRIBUTION_ORDER_PROCESS_TYPE" placeholder="未完成配送订单处理方式" clearable />
          </el-form-item>
          <el-form-item key="isRebateMaturity" prop="isRebateMaturity" label="装修返利是否到期">
            <c-dict-select v-model="cooperationEndDTO.isRebateMaturity" dict-type-code="BOOLEANS" placeholder="装修返利是否到期" clearable />
          </el-form-item>
          <el-form-item key="isUnfulfilledOrder" prop="isUnfulfilledOrder" label="是否有未交订货">
            <c-dict-select v-model="cooperationEndDTO.isUnfulfilledOrder" dict-type-code="BOOLEANS" placeholder="是否有未交订货" clearable />
          </el-form-item>
          <el-form-item key="isUnfulfilledOrderSubmit" prop="isUnfulfilledOrderSubmit" label="未交订货数量是否已提交">
            <c-dict-select v-model="cooperationEndDTO.isUnfulfilledOrderSubmit" dict-type-code="BOOLEANS" placeholder="未交订货数量是否已提交" clearable />
          </el-form-item>
          <el-form-item key="isDevelopNewCustomer" prop="isDevelopNewCustomer" label="是否已开发新商家">
            <CDictRadio v-model="cooperationEndDTO.isDevelopNewCustomer" dict-type-code="BOOLEANS" />
          </el-form-item>
          <template v-if="hasNewCustomer">
            <el-form-item key="newCustomerDescribe" prop="newCustomerDescribe" label="新商/意向客户概况描述" :span="24">
              <el-input v-model="cooperationEndDTO.newCustomerDescribe" type="textarea" show-word-limit maxlength="1024" :autosize="{minRows: 2}" placeholder="新商/意向客户概况描述" />
              <p class="tip">请从经销商年龄、经济实力、卖场选址地理位置、（预）报图面积、保证金缴纳等情况进行描述</p>
            </el-form-item>
            <el-form-item key="remark" prop="remark" label="备注" :span="24">
              <el-input v-model="cooperationEndDTO.remark" type="textarea" show-word-limit maxlength="1024" :autosize="{minRows: 2}" placeholder="备注" />
            </el-form-item>
          </template>
        </el-form>
      </QupFormContainer>
    </c-title>
    <c-title title="经销商-门店信息">
      <ShopTable ref="shopTable" :table-data="shopBusinessDTOS" :cooperation-end="cooperationEndDTO" />
    </c-title>
    <c-title title="经销商-业务账号及送达方信息">
      <AccountAndSenderInfo :table-data="accountToDTOS" />
    </c-title>
    <c-title title="经销商-门店建设信息">
      <ShopConstructionInfo ref="shopConstructionInfoForm" :table-data="shopConstructDTOS" type="edit" />
    </c-title>
    <c-title v-if="!!decorateEnterpriseDTO.code" title="经销商-关联轻居商信息">
      <QupFormContainer :column="3">
        <el-form ref="decorateEnterpriseForm" :model="decorateEnterpriseDTO" :rules="decorateEnterpriseDTORules" label-width="160px">
          <el-form-item key="code" prop="code" label="轻居客户编码">
            <span>{{ decorateEnterpriseDTO.code }}</span>
          </el-form-item>
          <el-form-item key="name" prop="name" label="轻居客户名称">
            <span>{{ decorateEnterpriseDTO.name }}</span>
          </el-form-item>
          <el-form-item key="businessTypeName" prop="businessTypeName" label="轻居客户业务类型">
            <c-dict-range-view :value="decorateEnterpriseDTO.businessTypeName" dict-type-code="BOOLEANS" domain-code="marketing" app-code="slm" />
          </el-form-item>
          <el-form-item key="cityLevelName" prop="cityLevelName" label="城市级别">
            <c-dict-range-view :value="decorateEnterpriseDTO.cityLevelName" dict-type-code="CITY_LEVEL" domain-code="marketing" app-code="slm" />
          </el-form-item>
          <el-form-item key="operateArea" prop="operateArea" label="经营面积">
            <span>{{ decorateEnterpriseDTO.operateArea }}㎡</span>
          </el-form-item>
          <el-form-item key="cooperateStart" prop="cooperateStart" label="加盟时间">
            <span>{{ decorateEnterpriseDTO.cooperateStart }}</span>
          </el-form-item>
          <el-form-item key="isTransferSales" prop="isTransferSales" label="是否转让销量">
            <c-dict-select v-model="decorateEnterpriseDTO.isTransferSales" dict-type-code="BOOLEANS" placeholder="是否转让销量" clearable />
          </el-form-item>
          <el-form-item key="isRebateMaturity" prop="isRebateMaturity" label="装修返利是否到期">
            <c-dict-select v-model="decorateEnterpriseDTO.isRebateMaturity" dict-type-code="BOOLEANS" placeholder="装修返利是否到期" clearable />
          </el-form-item>
          <el-form-item key="isUnfulfilledOrder" prop="isUnfulfilledOrder" label="是否有未交订货">
            <c-dict-select v-model="decorateEnterpriseDTO.isUnfulfilledOrder" dict-type-code="BOOLEANS" placeholder="是否有未交订货" clearable />
          </el-form-item>
          <el-form-item v-if="[1, '1'].includes(decorateEnterpriseDTO.isUnfulfilledOrder)" key="isUnfulfilledOrderSubmit" prop="isUnfulfilledOrderSubmit" label="未交订货数量是否已提交">
            <c-dict-select v-model="decorateEnterpriseDTO.isUnfulfilledOrderSubmit" dict-type-code="BOOLEANS" placeholder="未交订货数量是否已提交" clearable />
          </el-form-item>
        </el-form>
      </QupFormContainer>
    </c-title>
    <c-title title="经销商-附件信息">
      <QupFormContainer v-if="!id || Object.keys(detail).length>0" :column="1">
        <el-form ref="attachmentForm" :model="attachment" :rules="formRules" label-width="170px">
          <el-form-item v-show="showA" key="ACCESS072" prop="ACCESS072" label="最近一次整改通知书" :span="24">
            <c-file-list v-model="attachment.ACCESS072" direct-del :model-id="id" view-type="list" type-code="ACCESS072" />
          </el-form-item>
          <!-- <template v-else-if="cooperationEndDTO.type==='B'"> -->
          <el-form-item v-show="showB" key="ACCESS082" prop="ACCESS082" label="自愿放弃说明书" :span="24">
            <c-file-list v-model="attachment.ACCESS082" direct-del :model-id="id" view-type="list" type-code="ACCESS082" />
          </el-form-item>
          <el-form-item v-show="showB" key="ACCESS083" prop="ACCESS083" label="商家手持身份证" :span="24">
            <c-file-list v-model="attachment.ACCESS083" direct-del :model-id="id" view-type="list" type-code="ACCESS083" />
          </el-form-item>
          <el-form-item v-show="showB" prop="1" label="自愿放弃说明书模板下载" :span="24">
            <div class="template-down" @click.stop="handleDownTemplate(ACCESS082.id)">
              <span>（零售）经销商自愿放弃经营权说明书模板</span>
              <i class="el-icon-download" />
            </div>
          </el-form-item>
          <el-form-item v-show="showB" prop="2" label="自愿放弃说明书签订指导下载" :span="24">
            <div class="template-down" @click.stop="handleDownTemplate(ACCESS084.id)">
              <span>（零售）经销商自愿放弃经营权说明书签订指导</span>
              <i class="el-icon-download" />
            </div>
          </el-form-item>
          <!-- </template> -->
          <!-- <template v-else-if="cooperationEndDTO.type==='C'"> -->
          <el-form-item v-if="showC" key="ACCESS085" prop="ACCESS085" label="交接证明" :span="24">
            <c-file-list v-model="attachment.ACCESS085" direct-del :model-id="id" view-type="list" type-code="ACCESS085" />
          </el-form-item>
          <el-form-item v-if="showC && isTransferSales" key="ACCESS086" prop="ACCESS086" label="关系证明" :span="24">
            <c-file-list v-model="attachment.ACCESS086" direct-del :model-id="id" view-type="list" type-code="ACCESS086" />
          </el-form-item>
          <el-form-item v-show="showC" prop="1" label="商家交接证明模板下载" :span="24">
            <div class="template-down" @click.stop="handleDownTemplate(ACCESS085.id)">
              <span>（零售）经销商交接证明模板</span>
              <i class="el-icon-download" />
            </div>
          </el-form-item>
          <!-- </template> -->
          <el-form-item v-show="showC" key="ACCESS111" prop="ACCESS111" label="交接双方现场签订照片" label-width="160px" :span="24">
            <c-file-list v-model="attachment.ACCESS111" direct-del :model-id="id" view-type="list" type-code="ACCESS111" />
          </el-form-item>
          <el-form-item v-show="showC" prop="2" label="交接双方现场签订照片模板下载" label-width="180px" :span="24">
            <div class="template-down" @click.stop="handleDownTemplate(ACCESS111.id)">
              <span>交接双方现场签订照片模板下载</span>
              <i class="el-icon-download" />
            </div>
          </el-form-item>
        </el-form>
      </QupFormContainer>
    </c-title>
    <div class="btn-center">
      <c-button type="default" @click="handleCancel">取消</c-button>
      <c-button type="primary" @click="handleSave">保存草稿</c-button>
      <c-button type="primary" @click="handleSubmit">提交</c-button>
    </div>
  </c-back-wrap>
</template>
<script>
import { detail, save, submit } from '@/api/channelTask2/termination'
import ShopTable from './ShopTable'
import AccountAndSenderInfo from '../../components/AccountAndSenderInfo'
import ShopConstructionInfo from '../../components/ShopConstructionInfo'
import CustomerBaseInfo from '../../components/CustomerBaseInfo'
import { shopListByCustomer, constructShopListByCustomer, accountByCustomer, getTemplateConfig, downTemplate, decorateEnterpriseByCustomer } from '@/api/channelTask2/change'

export default {
  name: 'AddEdit',
  components: {
    ShopTable,
    AccountAndSenderInfo,
    ShopConstructionInfo,
    CustomerBaseInfo
  },
  props: {
    id: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      detail: {},
      loading: false,
      customerFormData: {},
      activeName: 1,
      shopBusinessDTOS: [], // 经销商门店信息
      accountToDTOS: [], // 业务账号及送达方信息
      shopConstructDTOS: [], // 门店建设信息
      cooperationEndDTO: {
        reason: '',
        type: '',
        isTransferSales: '',
        distributionType: '',
        isRebateMaturity: '',
        isUnfulfilledOrder: '',
        isUnfulfilledOrderSubmit: '',
        isDevelopNewCustomer: '0',
        newCustomerDescribe: '',
        remark: ''
      }, // 经销商终止信息
      decorateEnterpriseDTO: {
        code: '',
        name: '',
        businessTypeName: '',
        cityLevelName: '',
        cooperateStart: '',
        isTransferSales: '',
        isRebateMaturity: '',
        isUnfulfilledOrder: '',
        isUnfulfilledOrderSubmit: ''
      }, // 关联轻居客户
      attachment: {
        ACCESS072: [],
        ACCESS082: [], // 自愿放弃说明书
        ACCESS083: [], // 商家手册身份证照片
        ACCESS085: [], // 交接证明
        ACCESS086: [], // 关系证明
        ACCESS111: []
      }, // 附件
      startObserve: false,
      // 配置
      ACCESS082: {},
      ACCESS084: {},
      ACCESS085: {},
      ACCESS111: {}
    }
  },
  computed: {
    isEdit() {
      return !!this.id
    },
    isHandover() {
      return this.cooperationEndDTO.type === 'C'
    },
    hasNewCustomer() {
      return [1, '1'].includes(this.cooperationEndDTO.isDevelopNewCustomer)
    },
    formRules() {
      return {
        reason: [{ required: true, message: '请输入合作终止原因', trigger: 'change' }],
        isOtherReceiveManagerKnow: [{ required: true, message: '请选择是否需要其他业务客户经理接收知晓', trigger: 'change' }],
        type: [{ required: true, message: '请选择合作终止类型', trigger: 'change' }],
        isDevelopNewCustomer: [{ required: true, message: '请选择是否已开发新商家', trigger: 'change' }],
        newCustomerDescribe: [{ required: this.hasNewCustomer, message: '请输入新商/意向客户概况描述', trigger: 'change' }],
        isTransferSales: [{ required: this.hasNewCustomer, message: '请选择是否转让销量', trigger: 'change' }],
        distributionType: [{ required: this.hasNewCustomer, message: '请选择未完成配送订单处理方式', trigger: 'change' }],
        isRebateMaturity: [{ required: this.hasNewCustomer, message: '请选择装修返利是否到期', trigger: 'change' }],
        isUnfulfilledOrder: [{ required: this.hasNewCustomer, message: '请选择是否有未交订货', trigger: 'change' }],
        isUnfulfilledOrderSubmit: [{ required: this.hasNewCustomer, message: '请选择未交订货数量是否已提交', trigger: 'change' }],
        ACCESS072: [{ required: true, validator: (r, v, c) => {
          if (!this.showA) {
            c()
            return
          }
          if (!v || v.length <= 0) {
            c(new Error('请上传最后一次整改通知书'))
          } else {
            c()
          }
        }, trigger: 'change' }],
        ACCESS082: [{ required: true, validator: (r, v, c) => {
          if (!this.showB) {
            c()
            return
          }
          if (!v || v.length <= 0) {
            c(new Error('请上传自愿放弃说明书'))
          } else {
            c()
          }
        }, trigger: 'change' }],
        ACCESS083: [{ required: true, validator: (r, v, c) => {
          if (!this.showB) {
            c()
            return
          }
          if (!v || v.length <= 0) {
            c(new Error('请上传商家手持身份证'))
          } else {
            c()
          }
        }, trigger: 'change' }],
        ACCESS085: [{ required: true, validator: (r, v, c) => {
          if (!this.showC) {
            c()
            return
          }
          if (!v || v.length <= 0) {
            c(new Error('请上传交接证明'))
          } else {
            c()
          }
        }, trigger: 'change' }],
        ACCESS086: [{ required: true, validator: (r, v, c) => {
          if (!this.showC) {
            c()
            return
          }
          if (!v || v.length <= 0) {
            c(new Error('请上传关系证明'))
          } else {
            c()
          }
        }, trigger: 'change' }],
        ACCESS111: [{ required: true, validator: (r, v, c) => {
          if (!this.showC) {
            c()
            return
          }
          if (!v || v.length <= 0) {
            c(new Error('请上传交接双方现场签订照片'))
          } else {
            c()
          }
        }, trigger: 'change' }]
      }
    },
    decorateEnterpriseDTORules() {
      return {
        isRebateMaturity: [{ required: true, message: '请选择装修返利是否到期', trigger: 'change' }],
        isTransferSales: [{ required: true, message: '请选择是否转让销量', trigger: 'change' }],
        isUnfulfilledOrder: [{ required: true, message: '请选择是否有未交订货', trigger: 'change' }],
        isUnfulfilledOrderSubmit: [{ required: true, message: '请选择未交订货数量是否已提交', trigger: 'change' }]
      }
    },
    showA() {
      return this.cooperationEndDTO.type === 'A'
    },
    showB() {
      return this.cooperationEndDTO.type === 'B'
    },
    showC() {
      return this.cooperationEndDTO.type === 'C'
    },
    isTransferSales() {
      return [1, '1'].includes(this.cooperationEndDTO.isTransferSales)
    }
  },
  watch: {
    'cooperationEndDTO.type': {
      handler(v) {
        this.$set(this.cooperationEndDTO, 'isTransferSales', '0')
        if (this.cooperationEndDTO.distributionType === 'B') {
          this.$set(this.cooperationEndDTO, 'distributionType', '')
        }
      }
    },
    isHandover: {
      handler(v) {
        if (!v) {
          this.$set(this.cooperationEndDTO, 'isTransferSales', '')
        }
      }
    }
  },
  created() {
    this.templateConfig()
    if (this.id) {
      this.getDetailData().then(res => {
        setTimeout(() => {
          this.startObserve = true
        }, 200)
      })
    } else {
      this.startObserve = true
    }
  },
  methods: {
    getDetailData() {
      this.loading = true
      return detail(this.id).then(res => {
        this.detail = res.data
        this.shopBusinessDTOS = (this.detail.shopBusinessDTOS || []).map(e => {
          e.afterBusinessType = (e.afterBusinessType || '').split(',')
          e.afterBusinessTypeName = (e.afterBusinessTypeName || '').split(',')
          return e
        })
        this.accountToDTOS = this.detail.accountToDTOS || []
        this.shopConstructDTOS = this.detail.shopConstructDTOS || []
        this.cooperationEndDTO = this.detail.cooperationEndDTO || {}
        this.decorateEnterpriseDTO = this.detail.decorateEnterpriseDTO || {}
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    handleCancel() {
      this.$goBackCall().then(this.$pageStack.pop)
    },
    handleTypeChange(v) {
      if (v === 'C') {
        this.$set(this.cooperationEndDTO, 'isDevelopNewCustomer', '1')
      }
    },
    handleDownTemplate(id) {
      downTemplate(id)
    },
    templateConfig() {
      getTemplateConfig('ACCESS082').then(res => {
        this.ACCESS082 = res
      })
      getTemplateConfig('ACCESS084').then(res => {
        this.ACCESS084 = res
      })
      getTemplateConfig('ACCESS085').then(res => {
        this.ACCESS085 = res
      })
      getTemplateConfig('ACCESS111').then(res => {
        this.ACCESS111 = res
      })
    },
    handleCustomerChange(customerCode) {
      this.changeResultTableData = []
      this.shopBusinessDTOS = []
      this.shopConstructDTOS = []
      this.accountToDTOS = []
      this.decorateEnterpriseDTO = {}
      if (customerCode) {
        this.getShopData(customerCode)
      }
    },
    getShopData(customerCode) {
      shopListByCustomer(customerCode).then(res => {
        this.shopBusinessDTOS = res.data.map(e => {
          e.afterBusinessType = (e.businessType || '').split(',')
          e.afterBusinessTypeName = (e.businessTypeName || '').split(',')
          return e
        })
      })
      constructShopListByCustomer(customerCode).then(res => {
        this.shopConstructDTOS = res.data
      })
      accountByCustomer(customerCode).then(res => {
        this.accountToDTOS = res.data
      })
      decorateEnterpriseByCustomer(customerCode).then(res => {
        this.decorateEnterpriseDTO = res.data || {}
      })
    },
    async validate() {
      const keys = 'customerBaseInfo shopTable shopConstructionInfoForm endForm decorateEnterpriseForm attachmentForm'.split(' ')
      for (const k of keys) {
        if (this.$refs[k] && this.$refs[k].validate) {
          await this.$refs[k].validate()
        }
      }
      return Promise.resolve(true)
    },
    getPostData() {
      const data = {}
      if (this.id) {
        Object.assign(data, this.$deepClone(this.detail))
      }
      Object.assign(data, this.$deepClone(this.customerFormData))
      data.accountToDTOS = this.$deepClone(this.accountToDTOS)
      data.cooperationEndDTO = this.$deepClone(this.cooperationEndDTO)
      data.decorateEnterpriseDTO = this.decorateEnterpriseDTO.code ? this.$deepClone(this.decorateEnterpriseDTO) : null
      data.shopBusinessDTOS = this.$deepClone(this.shopBusinessDTOS).map(e => {
        e = { ...e }
        const { afterBusinessType, afterBusinessTypeName } = e
        e.afterBusinessType = typeof afterBusinessType === 'string' ? afterBusinessType : (afterBusinessType || []).join(',')
        e.afterBusinessTypeName = typeof afterBusinessTypeName === 'string' ? afterBusinessTypeName : (afterBusinessTypeName || []).join(',')
        return e
      })
      data.shopConstructDTOS = this.$deepClone(this.shopConstructDTOS)
      data.attachmentDTOS = []
      if (data.cooperationEndDTO.type === 'A') {
        data.attachmentDTOS.push(...this.$getFiles(this.attachment.ACCESS072 || []))
      }
      if (data.cooperationEndDTO.type === 'B') {
        data.attachmentDTOS.push(...this.$getFiles(this.attachment.ACCESS082 || []))
        data.attachmentDTOS.push(...this.$getFiles(this.attachment.ACCESS083 || []))
      }
      if (data.cooperationEndDTO.type === 'C') {
        data.attachmentDTOS.push(...this.$getFiles(this.attachment.ACCESS085 || []))
        data.attachmentDTOS.push(...this.$getFiles(this.attachment.ACCESS086 || []))
        data.attachmentDTOS.push(...this.$getFiles(this.attachment.ACCESS111 || []))
      }

      data.type = 'I'
      if (!this.isHandover && data.cooperationEndDTO) {
        data.cooperationEndDTO.isTransferSales = ''
      }
      return data
    },
    handleSave() {
      return save(this.getPostData()).then(res => {
        this.$message.success('操作成功!')
        this.$pageStack.pop('onPage')
      })
    },
    handleSubmit() {
      return this.validate().then(() => {
        return submit(this.getPostData()).then(res => {
          this.$message.success('操作成功!')
          this.$pageStack.pop('onPage')
        })
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.change-table-title{
  display: flex;
  justify-content: flex-start;
  align-items: center;
  &>span{
    color: #333;
    font-size: 16px;
    font-weight: 600;
    margin-right: 10px;
  }
}
.template-down{
    // display: flex;
    // align-content: center;
    display: inline-block;
    cursor: pointer;
    &>*{
      margin-right: 10px;
      color: #333;
      font-weight: 600;
    }
}
.tip{
  color: red;
  font-size: 12px;
  margin: 0;
  padding-top: 4px;
}
</style>
